import sys
from pathlib import Path
import json

sys.path.append(str(Path(__file__).parent.parent))
from reqapi.api import BaseApi
from reqapi.models.user_info import UserInfoResponse
from com.response_decryptor import ResponseDecryptor

class UserInfoApi(BaseApi):
    """用户信息API"""
    
    def get_user_info(self):
        """获取用户信息
        
        Returns:
            UserInfoData: 用户信息数据
            
        Raises:
            Exception: 请求失败或业务处理失败时抛出异常
        """
        # API端点
        endpoint = "/api/youpin/bff/user/Account/getUserInfoForApp"
        url = f"{self.BASE_URL}{endpoint}"
        
        # 获取请求头 - 直接使用父类的通用请求头
        headers = self.common_headers
        
        # 打印请求信息
        print("=" * 50)
        print("用户信息API - 请求URL:")
        print(url)
        print("\n用户信息API - 请求头:")
        for key, value in headers.items():
            print(f"{key}: {value}")
        print("=" * 50)
        
        # 发送请求（必须用GET方法）
        response = self.interceptor.send_request(url, method="GET", headers=headers, need_encrypt=True)
        
        # 打印响应信息
        print("\n" + "=" * 50)
        print("用户信息API - 结构化响应:")
        print(json.dumps(response, indent=4, ensure_ascii=False))

        # 兼容老逻辑：业务状态码判断和错误打印
        code = response.get("Code") if response.get("Code") is not None else response.get("code")
        msg = response.get("Msg") if response.get("Msg") is not None else response.get("msg")
        if code != 0:
            print(f"服务器返回错误: 代码={code}, 消息={msg}")
            return None
        # 正常返回
        data = UserInfoResponse.from_dict(response).Data
        return data


def main():
    """测试用户信息API"""
    try:
        from com.db.order_account_manager import OrderAccountManager
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
            
        if not account:
            print("无法获取ID为1的账号")
            return
            
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = UserInfoApi(
            device_token=device_id,  # 使用device_id作为device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 发送请求
        user_info = api.get_user_info()
        
        # 打印结果
        if user_info is not None:
            print("\n用户信息获取成功！")
            print(f"用户ID: {user_info.UserId}")
            print(f"昵称: {user_info.NickName}")
            print(f"手机号: {user_info.Mobile}")
            print(f"余额: {user_info.Balance}")
            print(f"Steam ID: {user_info.SteamId}")
            print(f"Steam交易状态: {user_info.SteamTradeStatusTip}")
        
    except Exception as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    main()
